<template>
  <div class="app-container"  >
    <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="客户名称" prop="customerName">
        <el-input
          v-model="queryParams.customerName"
          placeholder="请输入客户名称"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="手机" prop="mobile">
        <el-input
          v-model="queryParams.mobile"
          placeholder="请输入手机"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="电话" prop="telephone">
        <el-input
          v-model="queryParams.telephone"
          placeholder="请输入电话"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="邮箱" prop="email">
        <el-input
          v-model="queryParams.email"
          placeholder="请输入邮箱"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="状态" prop="isAidut">
        <el-select v-model="queryParams.status" placeholder="请选择状态" clearable size="small">
           <el-option
                v-for="dict in statusOptions"
                :key="dict.dictValue"
                :label="dict.dictLabel"
                :value="dict.dictValue"
              />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="cyan" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>
    <el-table v-loading="loading" :data="customerList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
       <el-table-column label="客户编号" width="180" align="center" prop="customerCode" :show-overflow-tooltip="true">
      </el-table-column>
      <el-table-column label="客户名称" align="center" prop="customerName" :show-overflow-tooltip="true">
         <template slot-scope="scope">
           <el-link @click="openCustomer(scope.row)" :underline="false" type="primary" >{{scope.row.customerName}}</el-link>
        </template>
      </el-table-column>
      <!-- <el-table-column label="手机" align="center" prop="mobile" />
      <el-table-column label="电话" align="center" prop="telephone" />
      <el-table-column label="网址" align="center" prop="website" />
      <el-table-column label="邮箱" align="center" prop="email" /> -->
      <el-table-column label="负责人" align="center" prop="userNickName" />
      <el-table-column label="认领时间" align="center" prop="createTime" width="180">
              <template slot-scope="scope">
                <span>{{ parseTime(scope.row.createTime, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
              </template>
            </el-table-column>
      <el-table-column label="详细地址" align="center" prop="detailAddress" show-overflow-tooltip  />
      <el-table-column label="状态" align="left" prop="status">
        <template slot-scope="scope">
              <el-tag prop="status" v-for="(item, index) in statusOptions"  :type="scope.row.status==2?'success':'danger'"   v-if="scope.row.status==item.dictValue">{{item.dictLabel}}</el-tag>
          </template>
      </el-table-column>
      <el-table-column label="审核状态" align="center" prop="isAudit" >
        <template slot-scope="scope">
              <el-tag prop="isAudit" v-for="(item, index) in auditOptions"  :type="scope.row.isAudit==1?'success':'danger'"  v-if="scope.row.isAudit==item.dictValue">{{item.dictLabel}}</el-tag>
          </template>
      </el-table-column>
      <el-table-column label="审核人" align="center" prop="auditUserNickName" />
       <el-table-column label="审核时间" align="center" prop="auditTime" width="180">
              <template slot-scope="scope">
                <span>{{ parseTime(scope.row.auditTime, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
              </template>
            </el-table-column>

      <el-table-column label="审核意见" align="center" prop="auditNote" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width"  fixed="right" width="80">
        <template slot-scope="scope">
          <el-button
          v-if="scope.row.status==1"
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleVisit(scope.row)"
            v-hasPermi="['crm:customerVisit:add']"
          >写跟进</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-log"
            @click="handleShow(scope.row)"
            v-hasPermi="['crm:customer:query']"
          >查看</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <el-drawer
     size="50%"
     :with-header="false"
      :title="show.title" :visible.sync="show.open"
      >
        <customer  ref="customer" />
    </el-drawer>
    <el-dialog :title="visit.title" :visible.sync="visit.open" width="500px" append-to-body>
       <el-form ref="form" :model="form" :rules="rules" label-width="100px">
        <el-form-item label="走访类型" prop="visitType">
           <el-select
              v-model="form.visitType"
              placeholder="请选择"
              clearable
              size="small"
            >
              <el-option
                v-for="dict in visitTypeOptions"
                :key="dict.dictValue"
                :label="dict.dictLabel"
                :value="dict.dictValue"
              />
            </el-select>
        </el-form-item>
        <el-form-item label="走访内容" prop="content">
           <el-input type="textarea" v-model="form.content" placeholder="请输入走访内容" />
        </el-form-item>
        <el-form-item label="图片" prop="photos">
             <el-upload
                :file-list="photoList"
                :action="uploadUrl"
                class="avatar-uploader2"
                list-type="picture-card"
                :before-upload="beforeAvatarUpload"
                :on-progress="onLoading"
                :on-error="onPhotoError"
                :on-success="handlePhotoSuccess"
                :on-remove="handlePhotoRemove">
                <i class="el-icon-plus"></i>
              </el-upload>
              <!-- <el-dialog class="photoDialog" :visible.sync="dialogVisible">
                <img width="100%" :src="dialogImageUrl" alt="">
              </el-dialog> -->
        </el-form-item>
        <el-form-item label="联系人" prop="contactsIds">
          <el-select
              v-model="form.contactsIds"
              placeholder="请选择"
              clearable
              size="small"
            >
              <el-option
                v-for="item in customerContacts"
                :key="item.contactsId"
                :label="item.name"
                :value="item.contactsId"
              />
            </el-select>
        </el-form-item>
        <el-form-item label="下次联系时间" prop="nextTime">
          <el-date-picker clearable size="small" style="width: 200px"
            v-model="form.nextTime"
            type="date"
            value-format="yyyy-MM-dd"
            placeholder="选择下次联系时间">
          </el-date-picker>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="visitSubmitForm">确 定</el-button>
        <el-button @click="visitCancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { myListCustomer,importTemplate,receive,getCustomer, delCustomer, addCustomer, updateCustomer, exportCustomer } from "@/api/crm/customer";
import { listCustomerVisit, getCustomerVisit, delCustomerVisit, addCustomerVisit, updateCustomerVisit, exportCustomerVisit } from "@/api/crm/customerVisit";
import { getToken } from "@/utils/auth";
import { treeselect } from "@/api/system/dept";
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";
import customer from "../../components/customerDetails";
import { getContactList  } from "@/api/crm/customerContacts";



export default {
  name: "Customer",
  components: { Treeselect,customer },
  data() {
    return {

      fileList: [],
      dialogVisible:false,
      baseUrl: process.env.VUE_APP_BASE_API,
      uploadUrl:process.env.VUE_APP_BASE_API+"/common/upload",
      photoList:[],
      images:[],
      dialogImageUrl: '',
      form:{},
      rules: {
        visitType: [
          { required: true, message: "请选择走访类型", trigger: "change" }
        ],
        contactsIds: [
          { required: true, message: "请选择联系人", trigger: "change" }
        ],
        content: [
          { required: true, message: "请输入走访内容", trigger: "change" }
        ]


      },
      visit:{

        open:false,
        title:'客户详情'
      },
      show:{
        open:false,
        title:'客户详情'
      },
      auditOptions:[],
      markersArray:[],
      map:{
        open:false,
        title:'地图选择'
      },
       // 导入参数
      upload: {
        // 是否显示弹出层（用户导入）
        open: false,
        // 弹出层标题（用户导入）
        title: "",
        // 是否禁用上传
        isUploading: false,
        // 是否更新已经存在的用户数据
        updateSupport: 0,
        // 设置上传的请求头部
        headers: { Authorization: "Bearer " + getToken() },
        // 上传的地址
        url: process.env.VUE_APP_BASE_API + "/crm/customer/importData",
      },
      deptOptions:[],
      statusOptions:[],
      receiveOptions:[],
      visitTypeOptions:[],
      customerContacts:[],
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 客户表格数据
      customerList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        customerName: null,
        mobile: null,
        telephone: null,
        website: null,
        email: null,
        createUserId: null,
        address: null,
        location: null,
        detailAddress: null,
        lng: null,
        lat: null,
        status: null,
        isReceive: null,
        deptId: null,
        isDel: null
      },
      loadingModel:null,


    };
  },
  created() {

    this.getList();
     this.getDicts("customer_user_status").then((response) => {
      this.statusOptions = response.data;
    });
    this.getDicts("customer_user_audit").then((response) => {
      this.auditOptions = response.data;
    });
    this.getDicts("customer_receive").then((response) => {
      this.receiveOptions = response.data;
    });
    this.getDicts("customer_visit_type").then((response) => {
      this.visitTypeOptions = response.data;
    });

  },
  mounted() {

  },
  methods: {
    onPhotoError(err, file, fileList){
        this.loadingModel.close();
    },
    onLoading(event, file, fileList){
        this.loadingModel = this.$loading({
          lock: true,
          text: 'Loading',
          spinner: 'el-icon-loading',
          background: 'rgba(0, 0, 0, 0.7)'
        });
    },
    beforeAvatarUpload(file) {
        const isJPG = file.type === 'image/jpeg';
        const isLt2M = file.size / 1024 / 1024 < 2;
        // if (!isJPG) {
        //   this.$message.error('上传图片只能是 JPG 格式!');
        // }
        if (!isLt2M) {
          this.$message.error('上传图片大小不能超过 2MB!');
        }
        return isLt2M;
      },
    handleChange(file, fileList) {
        this.fileList = fileList.slice(-3);
      },
     handlePhotoSuccess(res, file) {
        console.log(res);
        if(res.code==200){
          console.log(this.images)
          this.images.push(res.fileName);
        }
        else{
          this.msgError(res.msg);
        }
        this.loadingModel.close();

    },
    handlePhotoRemove(file, fileList) {
       let url="";
       if(file.response!=undefined){
         url=file.response.url;
       }
       else{
         url=file.url;
       }
      for(var i=0;i<this.images.length;i++){
          if(url==this.images[i]){
            this.images.splice(i,1);
          }
      }
    },
     handlePictureCardPreview(file) {
      this.dialogImageUrl = file.url;
      this.dialogVisible = true;
    },
    // 表单重置
    reset() {
      this.form = {
        visitId: null,
        customerUserId: null,
        customerId: null,
        visitType: null,
        content: null,
        photos: null,
        contactsIds: null,
        nextTime: null,
        lng: null,
        lat: null,
        address: null,
        createUserId: null,
        createTime: null
      };
      this.resetForm("form");
    },
    handleVisit(row){
      this.reset();
      this.images=[];
      this.fileList=[];
      this.photoList=[];
      this.form.photos="";
      this.form.customerUserId=row.customerUserId;
      this.form.customerId=row.customerId;
      this.visit.open = true;
      var data={customerId:this.form.customerId};
      getContactList(data).then(response => {
        if (response.code === 200) {
          this.customerContacts=response.list;
        }
      });
      this.visit.title = "写跟进";

    },
    visitSubmitForm(row){
      this.$refs["form"].validate(valid => {
        if (valid) {
            if(this.images!=null&&this.images.length>0){
                this.form.photos="";
                for(var i=0;i<this.images.length;i++){
                  this.form.photos+=this.images[i]+",";
                }
                this.form.photos=this.form.photos.substr(0,this.form.photos.length-1);
            }
            addCustomerVisit(this.form).then(response => {
              if (response.code === 200) {
                this.msgSuccess("提交成功");
                this.visit.open = false;
                this.getList();
              }
            });

        }
      });
    },
    visitCancel(){
        this.visit.open = false;
    },
    openCustomer(row){
      this.show.open=true;
      const customerId = row.customerId || this.ids
      setTimeout(() => {
        this.$refs.customer.getCustomerDetails(customerId);
      }, 500);
    },
    handleShow(row) {
      this.show.open=true;
      const customerId = row.customerId || this.ids
      setTimeout(() => {
        this.$refs.customer.getCustomerDetails(customerId);
      }, 500);

    },
    /** 查询客户列表 */
    getList() {
      this.loading = true;
      myListCustomer(this.queryParams).then(response => {
        this.customerList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },


    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.customerId)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    audit() {
       updateCustomer(this.form).then(response => {
              if (response.code === 200) {
                this.msgSuccess("修改成功");
                this.open = false;
                this.getList();
              }
            });
    },


  }
};
</script>
<style>


.photoDialog{
  z-index: 10000;
}
</style>
